package com.fudan.es.entity;

import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.search.aggregations.AggregationBuilder;

import com.fudan.es.Aggs;
import com.fudan.es.aggs.ConstString;

public abstract class Pack {

	protected final String ROOT_PATH = ConstString.ROOT_PATH;

	protected AggregationBuilder root;
	protected Map<String,AggregationBuilder> reverseAggsMap;
	protected Map<String,AggregationBuilder> nestedAggsMap;

	protected AggregationBuilder getreverseByPath(String path) {
		if(reverseAggsMap == null) {
			reverseAggsMap = new HashMap<>();
		}
		if(path == null) path = ROOT_PATH;
		AggregationBuilder reverseAggs = reverseAggsMap.get(path);
		if(reverseAggs == null) {
			if(path == null || path.equals(ROOT_PATH)) {
				reverseAggs = Aggs.reverse(ROOT_PATH);
				reverseAggsMap.put(ROOT_PATH, reverseAggs);
			}else {
				reverseAggs = Aggs.reverse(path,path);
				reverseAggsMap.put(path, reverseAggs);
			}
			root.subAggregation(reverseAggs);
		}
		return reverseAggs;
	}

	protected AggregationBuilder getNestedByPath(String path) {
		if(nestedAggsMap == null) {
			nestedAggsMap = new HashMap<>();
		}
		if(path == null) path = ROOT_PATH;
		AggregationBuilder nestedAggs = nestedAggsMap.get(path);
		if(nestedAggs == null) {
			nestedAggs = Aggs.nested(path, path);
			nestedAggsMap.put(path, nestedAggs);
			root.subAggregation(nestedAggs);
		}
		return nestedAggs;
	}
}
